package cn.edu.zafu.bigdata.yt.wjcz;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class FileReadWrite_yt {

    // 将用户输入的文本写入到指定的文件中
    public static void writeToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
            writer.write(content);
        } catch (IOException e) {
            System.out.println("An error occurred while writing to the file: " + e.getMessage());
        }
    }

    // 读取文件内容并将其打印到控制台
    public static void readFromFile(String fileName) {
        try (FileReader reader = new FileReader(fileName)) {
            int i;
            while ((i = reader.read()) != -1) {
                System.out.print((char) i);
            }
        } catch (IOException e) {
            System.out.println("An error occurred while reading the file: " + e.getMessage());
        }
    }

    // 主方法，用于测试写入和读取文件的功能
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter your student ID:");
        String studentId = scanner.nextLine();
        System.out.println("Please enter the text you want to save:");
        String text = scanner.nextLine();

        // 构建文件名，例如：files/2022010101.txt
        String fileName = "files/" + studentId + ".txt";

        // 将用户输入的文本写入文件
        writeToFile(fileName, text);

        // 读取文件内容并显示
        System.out.println("The content of the file " + fileName + " is:");
        readFromFile(fileName);

        scanner.close();
    }
}
